#include <head.h>
union semun
{
    int val;
    struct semid_ds *buf;
    unsigned short *arry;
};

int P(int semid, int semnum)  //等待信号灯 类似于无名信号量的P操作
{
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op = -1;
    sem_b.sem_flg = SEM_UNDO;
    if (semop(semid, &sem_b, 1) == -1)
    {
        perror("semop error ");
        return -1;
    }
    return 0; 
}

int V(int semid, int semnum)  //释放信号灯 类似于无名信号量的V操作
{
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op = 1;
    sem_b.sem_flg = SEM_UNDO;
    if (semop(semid, &sem_b, 1) == -1)
    {
        perror("semop error ");
        return -1;
    }
    return 0;
}

int del(int semid)
{
 if(semctl(semid, 0, IPC_RMID)==-1)
{
    perror("semid err");
    return -1;
}
return 0;
}

int main(int argc, char const *argv[])
{
    int shmid, semid;
    key_t key = ftok("./", 'A');
    if (key < 0)
    {
        perror("FTOK err");
    }
    if ((semid = semget(key, 2, IPC_CREAT | IPC_EXCL | 0666)) <= 0)
    {
        if (errno == EEXIST)
        {
            semid = semget(key, 2, 0666);
        }
        else
        {
            perror("semget err");
            return 0;
        }
    }
    else
    {
        union semun sem_union;
        sem_union.val = 1;
        semctl(semid, 0, SETVAL, sem_union);
    }
    while (1)
    {
        P(semid, 1);
        printf("%s\n", "墨阳黎");
        V(semid, 0);
    }
    if(del(semid)!=-1)
     printf("销毁成功");
    return 0;
}
